var app = getApp();
var starscore = require("../../templates/starscore/starscore.js");
var md5 = require("../../utils/md5.js");
var WxParse = require('../../templates/wxParse/wxParse.js');
//var server = require('../../utils/server');
Page({
	data: {
		onLoadStatus: true,
		indicatorDots: true,
		loadingStatus: false, // loading
		loadingFinish: false,
		shopLogo: '',
		shop_content: false,
		shopPrompt: [],
		shopDelivery: [],
		swiperCurrent: 0,
		selectCurrent: 0,
		categories: [],
		activeCategoryId: 0,
		goods: [],
		goodsList: [],
		goodsListCurrent:[],
		scrollTop: 0,
		page: 1,
		pageSize: 5000,
		classifyViewed: 0,
		width: 0,
		height: 0,
    shopPrompt:'我们的店铺上线了',
    width: wx.getStorageSync('width'),
    height: wx.getStorageSync('height'),
		movable: {
			text: '                                                                           '
		},
	},
	onLoad: function (options) {
		var that = this
    var shop_id = app.globalData.shopId;
    if (shop_id == 1067) {
      var now = new Date().getTime();
      var time1 = new Date('2018-08-01 00:00:00').getTime();
      var time2 = new Date('2018-08-05 23:59:59').getTime();
      if (now > time1 && now < time2) {
        this.setData({
          shopPrompt: '泰芒了入驻我的生活圈送好礼，购买店内任一款饮品送价值30元泰芒经典杯！'
        });
      }
    }
		wx.setNavigationBarTitle({
			title: ''
		})
    console.log(app.globalData.categories);
		that.setData({
			categories: app.globalData.categories,
			goods: app.globalData.goods,
			goodsList: app.globalData.goodsList,
			onLoadStatus: app.globalData.onLoadStatus,
			activeCategoryId: app.globalData.activeCategoryId,
      open_id: app.globalData.openId,
      user_id: app.globalData.userId,
		})
		for (var i = 0; i < that.data.categories.length; i++) {
			if (that.data.activeCategoryId === that.data.categories[i].id) {
				that.setData({
					classifyViewed: that.data.categories[i].id,
					scrolltop: 0,
					goodsListCurrent: that.data.goodsList[i],
				})
			}
		}

		//获取系统信息  
		wx.getSystemInfo({
			//获取系统信息成功，将系统窗口的宽高赋给页面的宽高  
			success: function (res) {
				//console.log(res.windowWidth)
				that.width = res.windowWidth / 2.9  //2.6
				that.height = res.windowWidth / 2.9  //2.6
			}
		})
		//console.log(this.width, this.height)
		if (!that.data.onLoadStatus) {
			that.showDialog('.onLoad-err')
		}
		that.getGoods(0);
	},
  onReady: function () {
    //调用canvasClock函数  
    this.canvasClock()
    //对canvasClock函数循环调用  
    this.interval = setInterval(this.canvasClock, 1000)
  },
	//事件处理函数
	tapClassify: function (e) {
		var that = this;
		var id = e.target.dataset.id;
		if (id === that.data.classifyViewed){
			that.setData({
				scrolltop: 0,
			})
		}else{
			that.setData({
				classifyViewed: id,
			});
			console.log('id:', that.data.classifyViewed)
			for (var i = 0; i < that.data.categories.length; i++) {
				if (id === that.data.categories[i].id) {
					that.setData({
						page: 1,
						scrolltop: 0,
						goodsListCurrent: that.data.goodsList[i]
					})
				}
			}
		}
	},
	toDetailsTap: function (e) {
		wx.navigateTo({
			url: "/pages/goods-details/index?id=" + e.currentTarget.dataset.id
		})
	},
	getGoods: function (categoryId) {
		if (categoryId == 0) {
			categoryId = "";
		}
		
      
	    var service = 'Shop.GetShopInfo';
      var shop_id = app.globalData.shopId;
      var openid = app.globalData.openId;
      var user_id = app.globalData.userId;
	    var sign = md5.md5(openid + service + shop_id + user_id);
		
	    var that = this;
	    wx.request({
	    	url: app.globalData.serviceUrl + 'Shop.GetShopInfo',
	    	header: {
	    		'Content-Type': 'json'
	    	},
	    	data: {
	    		openid: openid,
	    		shop_id: shop_id,
	    		user_id: user_id,
	    		sign: sign,
	    	},
	    	success: function (res) {
	    		if (res.data.data.code == 0) {
	    			that.setData({
	    				shopLogo: res.data.data.info.shop_pic_small,
	    				shop_content: res.data.data.info.shop_content,
	    				shop_name: res.data.data.info.shop_name,
	    				shop_address: res.data.data.info.shop_address,
		    		});
	    		}
	    		var goods = [];
	    		for(var i=0; i<res.data.data.info.shop_product.length; i++){
            var good = res.data.data.info.shop_product[i]
            var xing = [];
            if (good.product_fen > 0 && good.product_fen < 1) {
              xing.push('https://hongbao.zntech-china.com/attachment/images/wxcx/0.5star.png');
              for (var x = 0; x < 4; x++) {
                xing.push('https://hongbao.zntech-china.com/attachment/images/wxcx/0star.png');
              }
            } else if (good.product_fen == 1) {
              xing.push('https://hongbao.zntech-china.com/attachment/images/wxcx/1star.png');
              for (var x = 0; x < 4; x++) {
                xing.push('https://hongbao.zntech-china.com/attachment/images/wxcx/0star.png');
              }
            } else if (good.product_fen > 1 && good.product_fen < 2) {
              xing.push('https://hongbao.zntech-china.com/attachment/images/wxcx/1star.png');
              xing.push('https://hongbao.zntech-china.com/attachment/images/wxcx/0.5star.png');
              for (var x = 0; x < 3; x++) {
                xing.push('https://hongbao.zntech-china.com/attachment/images/wxcx/0star.png');
              }
            } else if (good.product_fen == 2) {
              xing.push('https://hongbao.zntech-china.com/attachment/images/wxcx/1star.png');
              xing.push('https://hongbao.zntech-china.com/attachment/images/wxcx/1star.png');
              for (var x = 0; x < 3; x++) {
                xing.push('https://hongbao.zntech-china.com/attachment/images/wxcx/0star.png');
              }
            } else if (good.product_fen > 2 && good.product_fen < 3) {
              xing.push('https://hongbao.zntech-china.com/attachment/images/wxcx/1star.png');
              xing.push('https://hongbao.zntech-china.com/attachment/images/wxcx/1star.png');
              xing.push('https://hongbao.zntech-china.com/attachment/images/wxcx/0.5star.png');
              for (var x = 0; x < 2; x++) {
                xing.push('https://hongbao.zntech-china.com/attachment/images/wxcx/0star.png');
              }
            } else if (good.product_fen == 3) {
              for (var x = 0; x < 3; x++) {
                xing.push('https://hongbao.zntech-china.com/attachment/images/wxcx/1star.png');
              }
              xing.push('https://hongbao.zntech-china.com/attachment/images/wxcx/0star.png');
              xing.push('https://hongbao.zntech-china.com/attachment/images/wxcx/0star.png');
            } else if (good.product_fen > 3 && good.product_fen < 4) {
              for (var x = 0; x < 3; x++) {
                xing.push('https://hongbao.zntech-china.com/attachment/images/wxcx/1star.png');
              }
              xing.push('https://hongbao.zntech-china.com/attachment/images/wxcx/0.5star.png');
              xing.push('https://hongbao.zntech-china.com/attachment/images/wxcx/0star.png');
            } else if (good.product_fen == 4) {
              for (var x = 0; x < 4; x++) {
                xing.push('https://hongbao.zntech-china.com/attachment/images/wxcx/1star.png');
              }
              xing.push('https://hongbao.zntech-china.com/attachment/images/wxcx/0star.png');
            } else if (good.product_fen > 4 && good.product_fen < 5) {
              for (var x = 0; x < 4; x++) {
                xing.push('https://hongbao.zntech-china.com/attachment/images/wxcx/1star.png');
              }
              xing.push('https://hongbao.zntech-china.com/attachment/images/wxcx/0.5star.png');
            } else {
              for (var x = 0; x < 5; x++) {
                if (good.product_fen==5){
                  xing.push('https://hongbao.zntech-china.com/attachment/images/wxcx/1star.png');
                }else{
                  xing.push('https://hongbao.zntech-china.com/attachment/images/wxcx/0star.png');
                }
              }
            }
            good['starpic'] = xing
            goods.push(good);
          }

	    		var state = {'3': '进行中','4': '已结束'};
	    		that.setData({
		        	goods: goods,
		        	shopDesc: '浏览量：' + res.data.data.info.shop_view + '     红包金额:' + res.data.data.info.shop_red_money + '     红包状态:' + state[res.data.data.info.shop_red_pid],
		        });
	    		WxParse.wxParse('article', 'html', res.data.data.info.shop_content, that, 0);
	    		wx.setStorageSync('mallInfo', res.data.data.info);
	    	},
	    	complete: function(res) {
	    		console.log(res);
	    	},
	    })
	},
  canvasClock: function () {
    var context = wx.createCanvasContext(this.canvasId, this)//创建并返回绘图上下文（获取画笔）  
    //设置宽高  
    var width = this.width
    var height = this.height
    var R = width / 4.5;//设置文字距离时钟中心点距离  
    //重置画布函数  
    function reSet() {
      context.height = context.height;//每次清除画布，然后变化后的时间补上  
      context.translate(width / 2.9, height / 2.9);//设置坐标轴原点  
      context.save();//保存中点坐标1  
    }
    //绘制中心圆和外面大圆  
    function circle() {
      //外面大圆  
      /*context.setLineWidth(1);
      context.beginPath();
      context.arc(0, 0, width / 2 - 30, 0, 2 * Math.PI, true);
      context.closePath();
      context.stroke();*/
      //中心圆  
      context.beginPath();
      context.arc(0, 0, 1.5, 0, 2 * Math.PI, true);
      context.closePath();
      context.stroke();
    }
    //绘制字体  
    function num() {
      // var R = width/2-60;//设置文字距离时钟中心点距离  
      context.setFontSize(width / 14)//设置字体样式  
      context.textBaseline = "middle";//字体上下居中，绘制时间  
      for (var i = 1; i < 13; i++) {
        //利用三角函数计算字体坐标表达式  
        var x = R * Math.cos(i * Math.PI / 6 - Math.PI / 2);
        var y = R * Math.sin(i * Math.PI / 6 - Math.PI / 2);
        if (i == 11 || i == 12) {//调整数字11和12的位置  
          context.fillText(i, x - width / 23, y + width / 30);
        } else if (i == 10) {//调整数字10的位置
          context.fillText(i, x - width / 25, y + width / 35);
        }
        else {
          context.fillText(i, x - width / 45, y + width / 48);
        }
      }
    }
    //绘制小格  
    function smallGrid() {
      context.setLineWidth(0.5);
      context.rotate(-Math.PI / 2);//时间从3点开始，倒转90度  
      for (var i = 0; i < 60; i++) {
        context.beginPath();
        context.rotate(Math.PI / 30);
        context.moveTo(width / 3.425, 0);
        context.lineTo(width / 3.75, 0);
        context.stroke();
      }
    }
    //绘制大格  
    function bigGrid() {
      context.setLineWidth(1);
      for (var i = 0; i < 12; i++) {
        context.beginPath();
        context.rotate(Math.PI / 6);
        context.moveTo(width / 3.42, 0);
        context.lineTo(width / 3.85, 0);
        context.stroke();
      }
    }
    //指针运动函数  
    function move() {
      var t = new Date();//获取当前时间  
      var h = t.getHours();//获取小时  
      h = h > 12 ? (h - 12) : h;//将24小时制转化为12小时制  
      var m = t.getMinutes();//获取分针  
      var s = t.getSeconds();//获取秒针  
      context.save();//再次保存2  
      //旋转角度=30度*（h+m/60+s/3600）  
      //分针旋转角度=6度*（m+s/60）  
      //秒针旋转角度=6度*s  

      //绘制时针  
      context.setLineWidth(1.2);
      context.beginPath();
      context.rotate((Math.PI / 6) * (h + m / 60 + s / 3600));
      context.moveTo(-width / 24, 0);//指针开始位置
      context.setLineCap('round')
      context.lineTo(width / 9, 0);//指针结束位置，可以决定指针长度
      context.stroke();
      context.restore();//恢复到2,（最初未旋转状态）避免旋转叠加  
      context.save();//3  
      //画分针  
      context.setLineWidth(0.8);
      context.beginPath();
      context.rotate((Math.PI / 30) * (m + s / 60));
      context.moveTo(-width / 24, 0);
      context.lineTo(width / 7.2, 0);
      context.stroke();
      context.restore();//恢复到3，（最初未旋转状态）避免旋转叠加  
      context.save();
      //绘制秒针  
      context.setLineWidth(0.5);
      context.beginPath();
      context.rotate((Math.PI / 30) * s);
      context.moveTo(-width / 24, 0);
      context.lineTo(width / 6.2, 0);
      context.stroke();
    }
    //调用  
    function drawClock() {
      reSet();
      circle();
      num();
      smallGrid();
      bigGrid();
      move();
    }
    drawClock()//调用运动函数  
    // 调用 wx.drawCanvas，通过 canvasId 指定在哪张画布上绘制，通过 actions 指定绘制行为  
    wx.drawCanvas({
      canvasId: 'myCanvas',
      actions: context.getActions()
    })
  },
  //页面卸载，清除画布绘制计时器  
  onUnload: function () {
    clearInterval(this.interval)
  },
  showDialog: function (dialogName) {
    let dialogComponent = this.selectComponent(dialogName)
    dialogComponent && dialogComponent.show();
  },
  hideDialog: function (dialogName) {
    let dialogComponent = this.selectComponent(dialogName)
    dialogComponent && dialogComponent.hide();
  },
  onConfirm: function () {
    this.hideDialog('.onLoad-err')
    this.reLoad()
  },
  onCancel: function () {
    this.hideDialog('.onLoad-err')
  },

  //分享小程序
  onShareAppMessage: function () {
    return {
      title: app.globalData.shopName,
      path: '/pages/start/start?shop_id=' + app.globalData.shopId,
      imageUrl: app.globalData.shopPic,
    }
  },
});

